<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  top20FiveStarStores,
  getFiveStarCountById,
  top20ReviewStores,
  getReviewCountById,
  getAvgScoreById,
  top10AvgScoreStores
} from '@/api/store'  // 你的接口方法
import { ratingDistribution } from "@/api/rating";
import { getAnnualRegistrations, userActivityByYear } from "@/api/user";

// 表格数据
const fiveStarStores = ref([])
const reviewStores = ref([])
const avgScoreStores = ref([])
const ratingDist = ref([])
const annualData = ref([])
const annualActivity = ref([])

const currentYear = new Date().getFullYear()
const fetchAnnualRegistrationsStartYear     = ref(currentYear - 5)
const fetchAnnualRegistrationsEndYear       = ref(currentYear)
const fetchAnnualActivityStartYear     = ref(currentYear - 5)
const fetchAnnualActivityEndYear       = ref(currentYear)

async function fetchTopFiveStarStores() {
  try {
    const res = await top20FiveStarStores()
    // 假设 res.data 就是 List<StoreDTO>，并且每条有 fiveStarCount 字段
    const list = res.data
    // 并发去拿每家店铺的五星好评数
    await Promise.all(
        list.map(async store => {
          const r = await getFiveStarCountById(store.id)
          // 把接口返回的 count 挂到对象上
          store.fiveStarCount = r.data
        })
    )
    // 最后赋值给表格
    fiveStarStores.value = list.slice()
    console.info(fiveStarStores)
  } catch (err) {
    console.error('fetchTopFiveStarStores error:', err)
    ElMessage.error('获取五星评论数据失败')
  }
}

async function fetchTopReviewStores() {
  try {
    const res = await top20ReviewStores()
    const list = res.data || []
    await Promise.all(
        list.map(async store => {
          const r = await getReviewCountById(store.id)
          store.reviewCount = r.data
        })
    )
    reviewStores.value = list.slice()
  } catch (err) {
    console.error('fetchTopReviewStores error:', err)
    ElMessage.error('获取评论数数据失败')
  }
}

async function fetchTopAvgScoreStores() {
  try {
    const res = await top10AvgScoreStores()
    const list = res.data || []
    await Promise.all(
        list.map(async store => {
          const r = await getAvgScoreById(store.id)
          store.avgScore = r.data
        })
    )
    avgScoreStores.value = list.slice()
  } catch (err) {
    console.error('fetchTopAvgScoreStores error:', err)
    ElMessage.error('获取平均分数据失败')
  }
}

async function fetchRatingDistribution() {
  try {
    const res = await ratingDistribution()
    ratingDist.value = res.data || []
    // 渲染 ECharts 饼图
    const chart = echarts.init(document.getElementById('rating-chart'))
    const option = {
      tooltip: { trigger: 'item' },
      legend: { orient: 'vertical', left: 'right' },
      series: [{
        name: '评分分布',
        type: 'pie',
        radius: '60%',
        data: ratingDist.value.map(d => ({
          name: `${d.star} 星`,
          value: d.count
        })),
        emphasis: {
          itemStyle: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0,0,0,0.3)' }
        }
      }]
    }
    chart.setOption(option)
  } catch (err) {
    console.error('fetchRatingDistribution error:', err)
    ElMessage.error('获取评分分布失败')
  }
}

async function fetchAnnualRegistrations(sy, ey) {
  try {
    const res = await getAnnualRegistrations({ startYear: sy, endYear: ey })
    annualData.value = res.data || []
  } catch (err) {
    ElMessage.error('获取年度注册数据失败')
  }
}

function initAnnualRegistrationsChart() {
  // 确保容器存在
  const chartEl = document.getElementById('chart-annual-registrations')
  if (!chartEl) return
  const chart = echarts.init(chartEl)
  const years = annualData.value.map(d => d.year)
  const counts = annualData.value.map(d => d.count)
  const option = {
    tooltip: {trigger: 'axis'},
    xAxis: {
      type: 'category',
      data: years,
      axisLabel: {rotate: 30}
    },
    yAxis: {
      type: 'value',
      name: '注册人数'
    },
    series: [{
      name: '注册数',
      type: 'bar',
      data: counts,
      barMaxWidth: '40%',
      itemStyle: {color: '#1E40AF'}
    }]
  }
  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

async function fetchAnnualActivity(sy, ey) {
  try {
    // 不传参则默认全量
    const res = await userActivityByYear({ startYear: sy, endYear: ey })
    annualActivity.value = res.data || []
  } catch (err) {
    console.error('fetchAnnualActivity error:', err)
    ElMessage.error('获取年度活跃度数据失败')
  }
}

function initAnnualActivityChart() {
  const el = document.getElementById('chart-annual-activity')
  if (!el) return
  const chart = echarts.init(el)

  const years       = annualActivity.value.map(d => d.year)
  const totalUsers  = annualActivity.value.map(d => d.totalUsers)
  const silentUsers = annualActivity.value.map(d => d.silentUsers)
  const activeRatio = annualActivity.value.map(d => d.activeRatio)

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    legend: {
      data: ['总用户', '沉默用户', '活跃率'],
      top: 0
    },
    xAxis: {
      type: 'category',
      data: years,
      axisLabel: { rotate: 30 }
    },
    yAxis: [
      {
        type: 'value',
        name: '用户数'
      },
      {
        type: 'value',
        name: '活跃率 (%)',
        axisLabel: { formatter: '{value}%' }
      }
    ],
    series: [
      {
        name: '总用户',
        type: 'bar',
        data: totalUsers,
        barMaxWidth: '30%',
        itemStyle: { color: '#1E40AF' }
      },
      {
        name: '沉默用户',
        type: 'bar',
        data: silentUsers,
        barMaxWidth: '30%',
        itemStyle: { color: '#3B82F6' }
      },
      {
        name: '活跃率',
        type: 'line',
        yAxisIndex: 1,
        data: activeRatio,
        smooth: true,
        lineStyle: { width: 3, color: '#0EA5E9' },
        symbol: 'circle',
        symbolSize: 8
      }
    ]
  }

  chart.setOption(option)
  window.addEventListener('resize', () => chart.resize())
}

async function refreshAnnualCharts() {
  // 验证年份输入
  if (fetchAnnualRegistrationsStartYear.value > fetchAnnualRegistrationsEndYear.value) {
    ElMessage.warning('开始年份不能大于结束年份')
    return
  }
  if (fetchAnnualActivityStartYear.value > fetchAnnualActivityEndYear.value) {
    ElMessage.warning('开始年份不能大于结束年份')
    return
  }

  await fetchAnnualRegistrations(fetchAnnualRegistrationsStartYear.value, fetchAnnualRegistrationsEndYear.value)
  initAnnualRegistrationsChart()
  await fetchAnnualActivity(fetchAnnualActivityStartYear.value, fetchAnnualActivityEndYear.value)
  initAnnualActivityChart()
}

onMounted(() => {
  fetchTopFiveStarStores()
  fetchTopReviewStores()
  fetchTopAvgScoreStores()
  fetchRatingDistribution()
  fetchAnnualRegistrations(fetchAnnualRegistrationsStartYear.value, fetchAnnualRegistrationsEndYear.value).then(() => {
    initAnnualRegistrationsChart()
  })
  fetchAnnualActivity(fetchAnnualActivityStartYear.value, fetchAnnualActivityEndYear.value).then(() => {
    initAnnualActivityChart()
  })
})
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <h1>数据分析</h1>
        <p class="header-desc">平台运营数据统计与分析</p>
      </div>
    </template>

    <!-- 五星评论最多前20 -->
    <div class="data-section">
      <div class="section-header">
        <h2>五星评论最多前20</h2>
        <p class="section-desc">展示平台内获得五星好评数量最多的前20家店铺</p>
      </div>
      <el-table
          :data="fiveStarStores"
          border
          stripe
          class="data-table"
          :row-class-name="(_, index) => index % 2 === 0 ? 'table-row-even' : ''"
      >
        <el-table-column prop="id" label="店铺ID" width="100"/>
        <el-table-column prop="name" label="店铺名称"/>
        <el-table-column prop="category" label="类别" width="150"/>
        <el-table-column prop="subCategory" label="子类别" width="150"/>
        <el-table-column prop="fiveStarCount" label="5星评论数" width="130">
          <template #default="scope">
            <span class="highlight-value">{{ scope.row.fiveStarCount }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 评论数最多前20 -->
    <div class="data-section">
      <div class="section-header">
        <h2>评论数最多前20</h2>
        <p class="section-desc">展示平台内获得用户评论数量最多的前20家店铺</p>
      </div>
      <el-table
          :data="reviewStores"
          border
          stripe
          class="data-table"
          :row-class-name="(_, index) => index % 2 === 0 ? 'table-row-even' : ''"
      >
        <el-table-column prop="id" label="店铺ID" width="100"/>
        <el-table-column prop="name" label="店铺名称"/>
        <el-table-column prop="category" label="类别" width="150"/>
        <el-table-column prop="subCategory" label="子类别" width="150"/>
        <el-table-column prop="reviewCount" label="评论数" width="130">
          <template #default="scope">
            <span class="highlight-value">{{ scope.row.reviewCount }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 平均分最高前10 -->
    <div class="data-section">
      <div class="section-header">
        <h2>平均分最高前10</h2>
        <p class="section-desc">展示平台内用户评分最高的前10家店铺</p>
      </div>
      <el-table
          :data="avgScoreStores"
          border
          stripe
          class="data-table"
          :row-class-name="(_, index) => index % 2 === 0 ? 'table-row-even' : ''"
      >
        <el-table-column prop="id" label="店铺ID" width="100"/>
        <el-table-column prop="name" label="店铺名称"/>
        <el-table-column prop="category" label="类别" width="150"/>
        <el-table-column prop="subCategory" label="子类别" width="150"/>
        <el-table-column prop="avgScore" label="平均分" width="130">
          <template #default="scope">
            <span class="highlight-value">{{ scope.row.avgScore.toFixed(1) }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 评分分布 -->
    <div class="data-section">
      <div class="section-header">
        <h2>评分分布</h2>
        <p class="section-desc">平台内用户对店铺评分的整体分布情况</p>
      </div>
      <div id="rating-chart" class="chart-container"></div>
    </div>

    <!-- 年度注册用户数 -->
    <div class="data-section">
      <div class="section-header">
        <h2>年度注册用户数</h2>
        <p class="section-desc">不同年份的平台新注册用户数量统计</p>
      </div>
      <div class="year-filter">
        <label>从</label>
        <el-input
            type="number"
            v-model.number="fetchAnnualRegistrationsStartYear"
            class="year-input"
            min="2000"
            max="2100"
        />
        <label>到</label>
        <el-input
            type="number"
            v-model.number="fetchAnnualRegistrationsEndYear"
            class="year-input"
            min="2000"
            max="2100"
        />
        <el-button
            type="primary"
            @click="refreshAnnualCharts"
            class="filter-btn"
        >
          刷新
        </el-button>
      </div>
      <div id="chart-annual-registrations" class="chart-container"></div>
    </div>

    <!-- 年度用户活跃度 -->
    <div class="data-section">
      <div class="section-header">
        <h2>年度用户活跃度</h2>
        <p class="section-desc">不同年份的平台用户活跃情况分析</p>
      </div>
      <div class="year-filter">
        <label>从</label>
        <el-input
            type="number"
            v-model.number="fetchAnnualActivityStartYear"
            class="year-input"
            min="2000"
            max="2100"
        />
        <label>到</label>
        <el-input
            type="number"
            v-model.number="fetchAnnualActivityEndYear"
            class="year-input"
            min="2000"
            max="2100"
        />
        <el-button
            type="primary"
            @click="refreshAnnualCharts"
            class="filter-btn"
        >
          刷新
        </el-button>
      </div>
      <div id="chart-annual-activity" class="chart-container"></div>
    </div>
  </el-card>
</template>

<style scoped lang="scss">
// 颜色变量
$primary: #1E40AF;
$primary-light: #3B82F6;
$primary-glass: rgba(30, 64, 175, 0.1);
$text-primary: #1E293B;
$text-secondary: #64748B;
$text-tertiary: #94A3B8;
$bg-light: #F8FAFC;
$white: #FFFFFF;
$border-color: #E2E8F0;
$shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
$transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

.page-container {
  width: 95%;
  max-width: 1400px;
  margin: 1.5rem auto;
  padding: 2rem;
  background: $white;
  border-radius: 12px;
  box-shadow: $shadow;
  border: none;
}

.header {
  padding-bottom: 1rem;
  border-bottom: 1px solid $border-color;

  h1 {
    font-size: 1.8rem;
    color: $primary;
    margin: 0 0 0.5rem;
    font-weight: 600;
  }

  .header-desc {
    color: $text-secondary;
    font-size: 1rem;
    margin: 0;
  }
}

.data-section {
  margin-top: 2.5rem;
  padding-top: 1rem;
  border-top: 1px solid $border-color;

  &:first-of-type {
    margin-top: 1.5rem;
    border-top: none;
    padding-top: 0;
  }

  .section-header {
    margin-bottom: 1.2rem;

    h2 {
      font-size: 1.3rem;
      color: $text-primary;
      margin: 0 0 0.4rem;
      font-weight: 600;
      display: flex;
      align-items: center;

      &::before {
        content: '';
        display: inline-block;
        width: 4px;
        height: 18px;
        background-color: $primary;
        border-radius: 2px;
        margin-right: 8px;
      }
    }

    .section-desc {
      color: $text-secondary;
      font-size: 0.9rem;
      margin: 0;
      padding-left: 12px;
    }
  }
}

.data-table {
  width: 100%;
  margin-bottom: 0.5rem;
  border-radius: 8px;
  overflow: hidden;

  th {
    background-color: $bg-light;
    color: $text-primary;
    font-weight: 500;
    height: 48px;
  }

  td {
    color: $text-primary;
    height: 45px;
    transition: $transition;

    &:hover {
      background-color: rgba(30, 64, 175, 0.02);
    }
  }

  .table-row-even {
    background-color: rgba(248, 250, 252, 0.5);
  }

  .highlight-value {
    color: $primary;
    font-weight: 500;
  }
}

.chart-container {
  width: 100%;
  height: 400px;
  margin-top: 0.8rem;
  background-color: $white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  padding: 1.2rem;
  transition: $transition;

  &:hover {
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  }
}

.year-filter {
  display: flex;
  align-items: center;
  gap: 0.8rem;
  margin-bottom: 1rem;
  padding-left: 2px;
  flex-wrap: wrap;

  label {
    color: $text-secondary;
    font-size: 0.9rem;
    white-space: nowrap;
  }

  .year-input {
    width: 100px;
    height: 36px;

    input {
      text-align: center;
    }
  }

  .filter-btn {
    background-color: $primary;
    border-color: $primary;

    &:hover {
      background-color: $primary-light;
      border-color: $primary-light;
    }
  }
}

// 响应式调整
@media (max-width: 1024px) {
  .chart-container {
    height: 350px;
  }
}

@media (max-width: 768px) {
  .page-container {
    padding: 1.2rem;
    width: 98%;
  }

  .data-section {
    margin-top: 2rem;
  }

  .chart-container {
    height: 300px;
    padding: 0.8rem;
  }

  .year-filter {
    gap: 0.5rem;
  }

  .year-input {
    width: 80px !important;
  }
}

@media (max-width: 576px) {
  .header h1 {
    font-size: 1.5rem;
  }

  .section-header h2 {
    font-size: 1.1rem;
  }

  .chart-container {
    height: 250px;
  }

  .data-table {
    font-size: 0.85rem;
  }

  .year-filter {
    flex-wrap: wrap;
  }

  .filter-btn {
    width: 100%;
    margin-top: 0.5rem;
  }
}
</style>